home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / patch20u.lha / patch-2.0.12u9 / patch.c < prev    next >
C/C++ Source or Header  |  1993-05-28  |  22KB  |  928 lines

  1. char rcsid[] =
  2.     "$Header: patch.c,v 2.0.2.0 90/05/01 22:17:50 davison Locked $";
  3.  
  4. /* patch - a program to apply diffs to original files
  5.  *
  6.  * Copyright 1986, Larry Wall
  7.  *
  8.  * This program may be copied as long as you don't try to make any
  9.  * money off of it, or pretend that you wrote it.
  10.  *
  11.  * $Log:    patch.c,v $
  12.  * Revision 2.0.2.0  90/05/01  22:17:50  davison
  13.  * patch12u: unidiff support added
  14.  * 
  15.  * Revision 2.0.1.6  88/06/22  20:46:39  lwall
  16.  * patch12: rindex() wasn't declared
  17.  * 
  18.  * Revision 2.0.1.5  88/06/03  15:09:37  lwall
  19.  * patch10: exit code improved.
  20.  * patch10: better support for non-flexfilenames.
  21.  * 
  22.  * Revision 2.0.1.4  87/02/16  14:00:04  lwall
  23.  * Short replacement caused spurious "Out of sync" message.
  24.  * 
  25.  * Revision 2.0.1.3  87/01/30  22:45:50  lwall
  26.  * Improved diagnostic on sync error.
  27.  * Moved do_ed_script() to pch.c.
  28.  * 
  29.  * Revision 2.0.1.2  86/11/21  09:39:15  lwall
  30.  * Fuzz factor caused offset of installed lines.
  31.  * 
  32.  * Revision 2.0.1.1  86/10/29  13:10:22  lwall
  33.  * Backwards search could terminate prematurely.
  34.  * 
  35.  * Revision 2.0  86/09/17  15:37:32  lwall
  36.  * Baseline for netwide release.
  37.  * 
  38.  * Revision 1.5  86/08/01  20:53:24  lwall
  39.  * Changed some %d's to %ld's.
  40.  * Linted.
  41.  * 
  42.  * Revision 1.4  86/08/01  19:17:29  lwall
  43.  * Fixes for machines that can't vararg.
  44.  * Added fuzz factor.
  45.  * Generalized -p.
  46.  * General cleanup.
  47.  * 
  48.  * 85/08/15 van%ucbmonet@berkeley
  49.  * Changes for 4.3bsd diff -c.
  50.  *
  51.  * Revision 1.3  85/03/26  15:07:43  lwall
  52.  * Frozen.
  53.  * 
  54.  * Revision 1.2.1.9  85/03/12  17:03:35  lwall
  55.  * Changed pfp->_file to fileno(pfp).
  56.  * 
  57.  * Revision 1.2.1.8  85/03/12  16:30:43  lwall
  58.  * Check i_ptr and i_womp to make sure they aren't null before freeing.
  59.  * Also allow ed output to be suppressed.
  60.  * 
  61.  * Revision 1.2.1.7  85/03/12  15:56:13  lwall
  62.  * Added -p option from jromine@uci-750a.
  63.  * 
  64.  * Revision 1.2.1.6  85/03/12  12:12:51  lwall
  65.  * Now checks for normalness of file to patch.
  66.  * 
  67.  * Revision 1.2.1.5  85/03/12  11:52:12  lwall
  68.  * Added -D (#ifdef) option from joe@fluke.
  69.  * 
  70.  * Revision 1.2.1.4  84/12/06  11:14:15  lwall
  71.  * Made smarter about SCCS subdirectories.
  72.  * 
  73.  * Revision 1.2.1.3  84/12/05  11:18:43  lwall
  74.  * Added -l switch to do loose string comparison.
  75.  * 
  76.  * Revision 1.2.1.2  84/12/04  09:47:13  lwall
  77.  * Failed hunk count not reset on multiple patch file.
  78.  * 
  79.  * Revision 1.2.1.1  84/12/04  09:42:37  lwall
  80.  * Branch for sdcrdcf changes.
  81.  * 
  82.  * Revision 1.2  84/11/29  13:29:51  lwall
  83.  * Linted.  Identifiers uniqified.  Fixed i_ptr malloc() bug.  Fixed
  84.  * multiple calls to mktemp().  Will now work on machines that can only
  85.  * read 32767 chars.  Added -R option for diffs with new and old swapped.
  86.  * Various cosmetic changes.
  87.  * 
  88.  * Revision 1.1  84/11/09  17:03:58  lwall
  89.  * Initial revision
  90.  * 
  91.  */
  92.  
  93. #include "INTERN.h"
  94. #include "common.h"
  95. #include "EXTERN.h"
  96. #include "version.h"
  97. #include "util.h"
  98. #include "pch.h"
  99. #include "inp.h"
  100. #include "backupfile.h"
  101.  
  102. /* procedures */
  103.  
  104. void reinitialize_almost_everything();
  105. void get_some_switches();
  106. LINENUM locate_hunk();
  107. void abort_hunk();
  108. void apply_hunk();
  109. void init_output();
  110. void init_reject();
  111. void copy_till();
  112. void spew_output();
  113. void dump_line();
  114. bool patch_match();
  115. bool similar();
  116. void re_input();
  117. void my_exit();
  118.  
  119. /* TRUE if -E was specified on command line.  */
  120. static int remove_empty_files = FALSE;
  121.  
  122. /* TRUE if -R was specified on command line.  */
  123. static int reverse_flag_specified = FALSE;
  124.  
  125. /* Apply a set of diffs as appropriate. */
  126.  
  127. int
  128. main(argc,argv)
  129. int argc;
  130. char **argv;
  131. {
  132.     LINENUM where;
  133.     LINENUM newwhere;
  134.     LINENUM fuzz;
  135.     LINENUM mymaxfuzz;
  136.     int hunk = 0;
  137.     int failed = 0;
  138.     int failtotal = 0;
  139.     bool rev_okayed = 0;
  140.     int i;
  141.  
  142.     setbuf(stderr, serrbuf);
  143.     for (i = 0; i<MAXFILEC; i++)
  144.     filearg[i] = Nullch;
  145.  
  146.     myuid = getuid();
  147.  
  148.     /* Cons up the names of the temporary files.  */
  149.     {
  150.       /* Directory for temporary files.  */
  151.       char *tmpdir;
  152.       int tmpname_len;
  153.  
  154.       tmpdir = getenv ("TMPDIR");
  155.       if (tmpdir == NULL) {
  156.     tmpdir = "/tmp";
  157.       }
  158.       tmpname_len = strlen (tmpdir) + 20;
  159.  
  160.       TMPOUTNAME = (char *) malloc (tmpname_len);
  161.       strcpy (TMPOUTNAME, tmpdir);
  162.       strcat (TMPOUTNAME, "/patchoXXXXXX");
  163.       Mktemp(TMPOUTNAME);
  164.  
  165.       TMPINNAME = (char *) malloc (tmpname_len);
  166.       strcpy (TMPINNAME, tmpdir);
  167.       strcat (TMPINNAME, "/patchiXXXXXX");
  168.       Mktemp(TMPINNAME);
  169.  
  170.       TMPREJNAME = (char *) malloc (tmpname_len);
  171.       strcpy (TMPREJNAME, tmpdir);
  172.       strcat (TMPREJNAME, "/patchrXXXXXX");
  173.       Mktemp(TMPREJNAME);
  174.  
  175.       TMPPATNAME = (char *) malloc (tmpname_len);
  176.       strcpy (TMPPATNAME, tmpdir);
  177.       strcat (TMPPATNAME, "/patchpXXXXXX");
  178.       Mktemp(TMPPATNAME);
  179.     }
  180.  
  181.     {
  182.       char *v;
  183.  
  184.       v = getenv ("SIMPLE_BACKUP_SUFFIX");
  185.       if (v)
  186.     simple_backup_suffix = v;
  187.       else
  188.     simple_backup_suffix = ORIGEXT;
  189. #ifndef NODIR
  190.       v = getenv ("VERSION_CONTROL");
  191.       backup_type = get_version (v); /* OK to pass NULL. */
  192. #endif
  193.     }
  194.  
  195.     /* parse switches */
  196.     Argc = argc;
  197.     Argv = argv;
  198.     get_some_switches();
  199.     
  200.     /* make sure we clean up /tmp in case of disaster */
  201.     set_signals(0);
  202.  
  203.     for (
  204.     open_patch_file(filearg[1]);
  205.     there_is_another_patch();
  206.     reinitialize_almost_everything()
  207.     ) {                    /* for each patch in patch file */
  208.  
  209.     if (outname == Nullch)
  210.         outname = savestr(filearg[0]);
  211.     
  212.     /* for ed script just up and do it and exit */
  213.     if (diff_type == ED_DIFF) {
  214.         do_ed_script();
  215.         continue;
  216.     }
  217.     
  218.     /* initialize the patched file */
  219.     if (!skip_rest_of_patch)
  220.         init_output(TMPOUTNAME);
  221.     
  222.     /* initialize reject file */
  223.     init_reject(TMPREJNAME);
  224.     
  225.     /* find out where all the lines are */
  226.     if (!skip_rest_of_patch)
  227.         scan_input(filearg[0]);
  228.     
  229.     /* from here on, open no standard i/o files, because malloc */
  230.     /* might misfire and we can't catch it easily */
  231.     
  232.     /* apply each hunk of patch */
  233.     hunk = 0;
  234.     failed = 0;
  235.     rev_okayed = FALSE;
  236.     out_of_mem = FALSE;
  237.     while (another_hunk()) {
  238.         hunk++;
  239.         fuzz = Nulline;
  240.         mymaxfuzz = pch_context();
  241.         if (maxfuzz < mymaxfuzz)
  242.         mymaxfuzz = maxfuzz;
  243.         if (!skip_rest_of_patch) {
  244.         do {
  245.             where = locate_hunk(fuzz);
  246.             if (hunk == 1 && where == Nulline && !(force|rev_okayed)) {
  247.                         /* dwim for reversed patch? */
  248.             if (!pch_swap()) {
  249.                 if (fuzz == Nulline)
  250.                 say1(
  251. "Not enough memory to try swapped hunk!  Assuming unswapped.\n");
  252.                 continue;
  253.             }
  254.             reverse = !reverse;
  255.             where = locate_hunk(fuzz);  /* try again */
  256.             if (where == Nulline) {        /* didn't find it swapped */
  257.                 if (!pch_swap())         /* put it back to normal */
  258.                 fatal1("lost hunk on alloc error!\n");
  259.                 reverse = !reverse;
  260.             }
  261.             else if (noreverse) {
  262.                 if (!pch_swap())         /* put it back to normal */
  263.                 fatal1("lost hunk on alloc error!\n");
  264.                 reverse = !reverse;
  265.                 say1(
  266. "Ignoring previously applied (or reversed) patch.\n");
  267.                 skip_rest_of_patch = TRUE;
  268.             }
  269.             else if (batch) {
  270.                 if (verbose)
  271.                 say3(
  272. "%seversed (or previously applied) patch detected!  %s -R.",
  273.                 reverse ? "R" : "Unr",
  274.                 reverse ? "Assuming" : "Ignoring");
  275.             }
  276.             else {
  277.                 ask3(
  278. "%seversed (or previously applied) patch detected!  %s -R? [y] ",
  279.                 reverse ? "R" : "Unr",
  280.                 reverse ? "Assume" : "Ignore");
  281.                 if (*buf == 'n') {
  282.                 ask1("Apply anyway? [n] ");
  283.                 if (*buf == 'y')
  284.                     rev_okayed = TRUE;
  285.                 else
  286.                     skip_rest_of_patch = TRUE;
  287.                 where = Nulline;
  288.                 reverse = !reverse;
  289.                 if (!pch_swap())  /* put it back to normal */
  290.                     fatal1("lost hunk on alloc error!\n");
  291.                 }
  292.             }
  293.             }
  294.         } while (!skip_rest_of_patch && where == Nulline &&
  295.             ++fuzz <= mymaxfuzz);
  296.  
  297.         if (skip_rest_of_patch) {        /* just got decided */
  298.             Fclose(ofp);
  299.             ofp = Nullfp;
  300.         }
  301.         }
  302.  
  303.         newwhere = pch_newfirst() + last_offset;
  304.         if (skip_rest_of_patch) {
  305.         abort_hunk();
  306.         failed++;
  307.         if (verbose)
  308.             say3("Hunk #%d ignored at %ld.\n", hunk, newwhere);
  309.         }
  310.         else if (where == Nulline) {
  311.         abort_hunk();
  312.         failed++;
  313.         if (verbose)
  314.             say3("Hunk #%d failed at %ld.\n", hunk, newwhere);
  315.         }
  316.         else {
  317.         apply_hunk(where);
  318.         if (verbose) {
  319.             say3("Hunk #%d succeeded at %ld", hunk, newwhere);
  320.             if (fuzz)
  321.             say2(" with fuzz %ld", fuzz);
  322.             if (last_offset)
  323.             say3(" (offset %ld line%s)",
  324.                 last_offset, last_offset==1L?"":"s");
  325.             say1(".\n");
  326.         }
  327.         }
  328.     }
  329.  
  330.     if (out_of_mem && using_plan_a) {
  331.         Argc = Argc_last;
  332.         Argv = Argv_last;
  333.         say1("\n\nRan out of memory using Plan A--trying again...\n\n");
  334.         if (ofp)
  335.             Fclose(ofp);
  336.         ofp = Nullfp;
  337.         if (rejfp)
  338.             Fclose(rejfp);
  339.         rejfp = Nullfp;
  340.         continue;
  341.     }
  342.     
  343.     assert(hunk);
  344.     
  345.     /* finish spewing out the new file */
  346.     if (!skip_rest_of_patch)
  347.         spew_output();
  348.     
  349.     /* and put the output where desired */
  350.     ignore_signals();
  351.     if (!skip_rest_of_patch) {
  352.         struct stat statbuf;
  353.         char *realout = outname;
  354.  
  355.         if (move_file(TMPOUTNAME, outname) < 0) {
  356.         toutkeep = TRUE;
  357.         realout = TMPOUTNAME;
  358.         chmod(TMPOUTNAME, filemode);
  359.         }
  360.         else
  361.         chmod(outname, filemode);
  362.  
  363.         if (remove_empty_files && stat(realout, &statbuf) == 0
  364.         && statbuf.st_size == 0) {
  365.         if (verbose)
  366.             say2("Removing %s (empty after patching).\n", realout);
  367.             while (unlink(realout) >= 0) ; /* while is for Eunice.  */
  368.         }
  369.     }
  370.     Fclose(rejfp);
  371.     rejfp = Nullfp;
  372.     if (failed) {
  373.         failtotal += failed;
  374.         if (!*rejname) {
  375.         Strcpy(rejname, outname);
  376. #ifndef FLEXFILENAMES
  377.         {
  378.             char *s = rindex(rejname,'/');
  379.  
  380.             if (!s)
  381.             s = rejname;
  382.             if (strlen(s) > 13)
  383.             if (s[12] == '.')    /* try to preserve difference */
  384.                 s[12] = s[13];    /* between .h, .c, .y, etc. */
  385.             s[13] = '\0';
  386.         }
  387. #endif
  388.         Strcat(rejname, REJEXT);
  389.         }
  390.         if (skip_rest_of_patch) {
  391.         say4("%d out of %d hunks ignored--saving rejects to %s\n",
  392.             failed, hunk, rejname);
  393.         }
  394.         else {
  395.         say4("%d out of %d hunks failed--saving rejects to %s\n",
  396.             failed, hunk, rejname);
  397.         }
  398.         if (move_file(TMPREJNAME, rejname) < 0)
  399.         trejkeep = TRUE;
  400.     }
  401.     set_signals(1);
  402.     }
  403.     my_exit(failtotal);
  404. }
  405.  
  406. /* Prepare to find the next patch to do in the patch file. */
  407.  
  408. void
  409. reinitialize_almost_everything()
  410. {
  411.     re_patch();
  412.     re_input();
  413.  
  414.     input_lines = 0;
  415.     last_frozen_line = 0;
  416.  
  417.     filec = 0;
  418.     if (filearg[0] != Nullch && !out_of_mem) {
  419.     free(filearg[0]);
  420.     filearg[0] = Nullch;
  421.     }
  422.  
  423.     if (outname != Nullch) {
  424.     free(outname);
  425.     outname = Nullch;
  426.     }
  427.  
  428.     last_offset = 0;
  429.  
  430.     diff_type = 0;
  431.  
  432.     if (revision != Nullch) {
  433.     free(revision);
  434.     revision = Nullch;
  435.     }
  436.  
  437.     reverse = reverse_flag_specified;
  438.     skip_rest_of_patch = FALSE;
  439.  
  440.     get_some_switches();
  441.  
  442.     if (filec >= 2)
  443.     fatal1("you may not change to a different patch file\n");
  444. }
  445.  
  446. static char *
  447. nextarg()
  448. {
  449.     if (!--Argc)
  450.     fatal2("missing argument after `%s'\n", *Argv);
  451.     return *++Argv;
  452. }
  453.  
  454. /* Process switches and filenames up to next '+' or end of list. */
  455.  
  456. void
  457. get_some_switches()
  458. {
  459.     Reg1 char *s;
  460.  
  461.     rejname[0] = '\0';
  462.     Argc_last = Argc;
  463.     Argv_last = Argv;
  464.     if (!Argc)
  465.     return;
  466.     for (Argc--,Argv++; Argc; Argc--,Argv++) {
  467.     s = Argv[0];
  468.     if (strEQ(s, "+")) {
  469.         return;            /* + will be skipped by for loop */
  470.     }
  471.     if (*s != '-' || !s[1]) {
  472.         if (filec == MAXFILEC)
  473.         fatal1("too many file arguments\n");
  474.         filearg[filec++] = savestr(s);
  475.     }
  476.     else {
  477.         switch (*++s) {
  478.         case 'b':
  479.         simple_backup_suffix = savestr(nextarg());
  480.         break;
  481.         case 'B':
  482.         origprae = savestr(nextarg());
  483.         break;
  484.         case 'c':
  485.         diff_type = CONTEXT_DIFF;
  486.         break;
  487.         case 'd':
  488.         if (!*++s)
  489.             s = nextarg();
  490.         if (chdir(s) < 0)
  491.             pfatal2("can't cd to %s", s);
  492.         break;
  493.         case 'D':
  494.             do_defines = TRUE;
  495.         if (!*++s)
  496.             s = nextarg();
  497.         if (!isalpha(*s) && '_' != *s)
  498.             fatal1("argument to -D is not an identifier\n");
  499.         Sprintf(if_defined, "#ifdef %s\n", s);
  500.         Sprintf(not_defined, "#ifndef %s\n", s);
  501.         Sprintf(end_defined, "#endif /* %s */\n", s);
  502.         break;
  503.         case 'e':
  504.         diff_type = ED_DIFF;
  505.         break;
  506.         case 'E':
  507.         remove_empty_files = TRUE;
  508.         break;
  509.         case 'f':
  510.         force = TRUE;
  511.         break;
  512.         case 'F':
  513.         if (*++s == '=')
  514.             s++;
  515.         maxfuzz = atoi(s);
  516.         break;
  517.         case 'l':
  518.         canonicalize = TRUE;
  519.         break;
  520.         case 'n':
  521.         diff_type = NORMAL_DIFF;
  522.         break;
  523.         case 'N':
  524.         noreverse = TRUE;
  525.         break;
  526.         case 'o':
  527.         outname = savestr(nextarg());
  528.         break;
  529.         case 'p':
  530.         if (*++s == '=')
  531.             s++;
  532.         strippath = atoi(s);
  533.         break;
  534.         case 'r':
  535.         Strcpy(rejname, nextarg());
  536.         break;
  537.         case 'R':
  538.         reverse = TRUE;
  539.         reverse_flag_specified = TRUE;
  540.         break;
  541.         case 's':
  542.         verbose = FALSE;
  543.         break;
  544.         case 'S':
  545.         skip_rest_of_patch = TRUE;
  546.         break;
  547.         case 't':
  548.         batch = TRUE;
  549.         break;
  550.         case 'u':
  551.         diff_type = UNI_DIFF;
  552.         break;
  553.         case 'v':
  554.         version();
  555.         break;
  556.         case 'V':
  557. #ifndef NODIR
  558.         backup_type = get_version (nextarg ());
  559. #endif
  560.         break;
  561. #ifdef DEBUGGING
  562.         case 'x':
  563.         debug = atoi(s+1);
  564.         break;
  565. #endif
  566.         default:
  567.         fprintf(stderr, "patch: unrecognized option `%s'\n", Argv[0]);
  568.         fprintf(stderr, "\
  569. Usage: patch [options] [origfile [patchfile]] [+ [options] [origfile]]...\n\
  570. Options:\n\
  571.        [-ceEflnNRsStuv] [-b backup-ext] [-B backup-prefix] [-d directory]\n\
  572.        [-D symbol] [-Fmax-fuzz] [-o out-file] [-p[strip-count]]\n\
  573.        [-r rej-name] [-V {numbered,existing,simple}]\n");
  574.         my_exit(1);
  575.         }
  576.     }
  577.     }
  578. }
  579.  
  580. /* Attempt to find the right place to apply this hunk of patch. */
  581.  
  582. LINENUM
  583. locate_hunk(fuzz)
  584. LINENUM fuzz;
  585. {
  586.     Reg1 LINENUM first_guess = pch_first() + last_offset;
  587.     Reg2 LINENUM offset;
  588.     LINENUM pat_lines = pch_ptrn_lines();
  589.     Reg3 LINENUM max_pos_offset = input_lines - first_guess
  590.                 - pat_lines + 1; 
  591.     Reg4 LINENUM max_neg_offset = first_guess - last_frozen_line - 1
  592.                 + pch_context();
  593.  
  594.     if (!pat_lines)            /* null range matches always */
  595.     return first_guess;
  596.     if (max_neg_offset >= first_guess)    /* do not try lines < 0 */
  597.     max_neg_offset = first_guess - 1;
  598.     if (first_guess <= input_lines && patch_match(first_guess, Nulline, fuzz))
  599.     return first_guess;
  600.     for (offset = 1; ; offset++) {
  601.     Reg5 bool check_after = (offset <= max_pos_offset);
  602.     Reg6 bool check_before = (offset <= max_neg_offset);
  603.  
  604.     if (check_after && patch_match(first_guess, offset, fuzz)) {
  605. #ifdef DEBUGGING
  606.         if (debug & 1)
  607.         say3("Offset changing from %ld to %ld\n", last_offset, offset);
  608. #endif
  609.         last_offset = offset;
  610.         return first_guess+offset;
  611.     }
  612.     else if (check_before && patch_match(first_guess, -offset, fuzz)) {
  613. #ifdef DEBUGGING
  614.         if (debug & 1)
  615.         say3("Offset changing from %ld to %ld\n", last_offset, -offset);
  616. #endif
  617.         last_offset = -offset;
  618.         return first_guess-offset;
  619.     }
  620.     else if (!check_before && !check_after)
  621.         return Nulline;
  622.     }
  623. }
  624.  
  625. /* We did not find the pattern, dump out the hunk so they can handle it. */
  626.  
  627. void
  628. abort_hunk()
  629. {
  630.     Reg1 LINENUM i;
  631.     Reg2 LINENUM pat_end = pch_end();
  632.     /* add in last_offset to guess the same as the previous successful hunk */
  633.     LINENUM oldfirst = pch_first() + last_offset;
  634.     LINENUM newfirst = pch_newfirst() + last_offset;
  635.     LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
  636.     LINENUM newlast = newfirst + pch_repl_lines() - 1;
  637.     char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
  638.     char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
  639.  
  640.     fprintf(rejfp, "***************\n");
  641.     for (i=0; i<=pat_end; i++) {
  642.     switch (pch_char(i)) {
  643.     case '*':
  644.         if (oldlast < oldfirst)
  645.         fprintf(rejfp, "*** 0%s\n", stars);
  646.         else if (oldlast == oldfirst)
  647.         fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
  648.         else
  649.         fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst, oldlast, stars);
  650.         break;
  651.     case '=':
  652.         if (newlast < newfirst)
  653.         fprintf(rejfp, "--- 0%s\n", minuses);
  654.         else if (newlast == newfirst)
  655.         fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
  656.         else
  657.         fprintf(rejfp, "--- %ld,%ld%s\n", newfirst, newlast, minuses);
  658.         break;
  659.     case '\n':
  660.         fprintf(rejfp, "%s", pfetch(i));
  661.         break;
  662.     case ' ': case '-': case '+': case '!':
  663.         fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
  664.         break;
  665.     default:
  666.         fatal1("fatal internal error in abort_hunk\n"); 
  667.     }
  668.     }
  669. }
  670.  
  671. /* We found where to apply it (we hope), so do it. */
  672.  
  673. void
  674. apply_hunk(where)
  675. LINENUM where;
  676. {
  677.     Reg1 LINENUM old = 1;
  678.     Reg2 LINENUM lastline = pch_ptrn_lines();
  679.     Reg3 LINENUM new = lastline+1;
  680. #define OUTSIDE 0
  681. #define IN_IFNDEF 1
  682. #define IN_IFDEF 2
  683. #define IN_ELSE 3
  684.     Reg4 int def_state = OUTSIDE;
  685.     Reg5 bool R_do_defines = do_defines;
  686.     Reg6 LINENUM pat_end = pch_end();
  687.  
  688.     where--;
  689.     while (pch_char(new) == '=' || pch_char(new) == '\n')
  690.     new++;
  691.     
  692.     while (old <= lastline) {
  693.     if (pch_char(old) == '-') {
  694.         copy_till(where + old - 1);
  695.         if (R_do_defines) {
  696.         if (def_state == OUTSIDE) {
  697.             fputs(not_defined, ofp);
  698.             def_state = IN_IFNDEF;
  699.         }
  700.         else if (def_state == IN_IFDEF) {
  701.             fputs(else_defined, ofp);
  702.             def_state = IN_ELSE;
  703.         }
  704.         fputs(pfetch(old), ofp);
  705.         }
  706.         last_frozen_line++;
  707.         old++;
  708.     }
  709.     else if (new > pat_end) {
  710.         break;
  711.     }
  712.     else if (pch_char(new) == '+') {
  713.         copy_till(where + old - 1);
  714.         if (R_do_defines) {
  715.         if (def_state == IN_IFNDEF) {
  716.             fputs(else_defined, ofp);
  717.             def_state = IN_ELSE;
  718.         }
  719.         else if (def_state == OUTSIDE) {
  720.             fputs(if_defined, ofp);
  721.             def_state = IN_IFDEF;
  722.         }
  723.         }
  724.         fputs(pfetch(new), ofp);
  725.         new++;
  726.     }
  727.     else if (pch_char(new) != pch_char(old)) {
  728.         say3("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
  729.         pch_hunk_beg() + old,
  730.         pch_hunk_beg() + new);
  731. #ifdef DEBUGGING
  732.         say3("oldchar = '%c', newchar = '%c'\n",
  733.         pch_char(old), pch_char(new));
  734. #endif
  735.         my_exit(1);
  736.     }
  737.     else if (pch_char(new) == '!') {
  738.         copy_till(where + old - 1);
  739.         if (R_do_defines) {
  740.            fputs(not_defined, ofp);
  741.            def_state = IN_IFNDEF;
  742.         }
  743.         while (pch_char(old) == '!') {
  744.         if (R_do_defines) {
  745.             fputs(pfetch(old), ofp);
  746.         }
  747.         last_frozen_line++;
  748.         old++;
  749.         }
  750.         if (R_do_defines) {
  751.         fputs(else_defined, ofp);
  752.         def_state = IN_ELSE;
  753.         }
  754.         while (pch_char(new) == '!') {
  755.         fputs(pfetch(new), ofp);
  756.         new++;
  757.         }
  758.     }
  759.     else {
  760.         assert(pch_char(new) == ' ');
  761.         old++;
  762.         new++;
  763.         if (R_do_defines && def_state != OUTSIDE) {
  764.         fputs(end_defined, ofp);
  765.         def_state = OUTSIDE;
  766.         }
  767.     }
  768.     }
  769.     if (new <= pat_end && pch_char(new) == '+') {
  770.     copy_till(where + old - 1);
  771.     if (R_do_defines) {
  772.         if (def_state == OUTSIDE) {
  773.             fputs(if_defined, ofp);
  774.         def_state = IN_IFDEF;
  775.         }
  776.         else if (def_state == IN_IFNDEF) {
  777.         fputs(else_defined, ofp);
  778.         def_state = IN_ELSE;
  779.         }
  780.     }
  781.     while (new <= pat_end && pch_char(new) == '+') {
  782.         fputs(pfetch(new), ofp);
  783.         new++;
  784.     }
  785.     }
  786.     if (R_do_defines && def_state != OUTSIDE) {
  787.     fputs(end_defined, ofp);
  788.     }
  789. }
  790.  
  791. /* Open the new file. */
  792.  
  793. void
  794. init_output(name)
  795. char *name;
  796. {
  797.     ofp = fopen(name, "w");
  798.     if (ofp == Nullfp)
  799.     pfatal2("can't create %s", name);
  800. }
  801.  
  802. /* Open a file to put hunks we can't locate. */
  803.  
  804. void
  805. init_reject(name)
  806. char *name;
  807. {
  808.     rejfp = fopen(name, "w");
  809.     if (rejfp == Nullfp)
  810.     pfatal2("can't create %s", name);
  811. }
  812.  
  813. /* Copy input file to output, up to wherever hunk is to be applied. */
  814.  
  815. void
  816. copy_till(lastline)
  817. Reg1 LINENUM lastline;
  818. {
  819.     Reg2 LINENUM R_last_frozen_line = last_frozen_line;
  820.  
  821.     if (R_last_frozen_line > lastline)
  822.     fatal1("misordered hunks! output would be garbled\n");
  823.     while (R_last_frozen_line < lastline) {
  824.     dump_line(++R_last_frozen_line);
  825.     }
  826.     last_frozen_line = R_last_frozen_line;
  827. }
  828.  
  829. /* Finish copying the input file to the output file. */
  830.  
  831. void
  832. spew_output()
  833. {
  834. #ifdef DEBUGGING
  835.     if (debug & 256)
  836.     say3("il=%ld lfl=%ld\n",input_lines,last_frozen_line);
  837. #endif
  838.     if (input_lines)
  839.     copy_till(input_lines);        /* dump remainder of file */
  840.     Fclose(ofp);
  841.     ofp = Nullfp;
  842. }
  843.  
  844. /* Copy one line from input to output. */
  845.  
  846. void
  847. dump_line(line)
  848. LINENUM line;
  849. {
  850.     Reg1 char *s;
  851.     Reg2 char R_newline = '\n';
  852.  
  853.     /* Note: string is not null terminated. */
  854.     for (s=ifetch(line, 0); putc(*s, ofp) != R_newline; s++) ;
  855. }
  856.  
  857. /* Does the patch pattern match at line base+offset? */
  858.  
  859. bool
  860. patch_match(base, offset, fuzz)
  861. LINENUM base;
  862. LINENUM offset;
  863. LINENUM fuzz;
  864. {
  865.     Reg1 LINENUM pline = 1 + fuzz;
  866.     Reg2 LINENUM iline;
  867.     Reg3 LINENUM pat_lines = pch_ptrn_lines() - fuzz;
  868.  
  869.     for (iline=base+offset+fuzz; pline <= pat_lines; pline++,iline++) {
  870.     if (canonicalize) {
  871.         if (!similar(ifetch(iline, (offset >= 0)),
  872.              pfetch(pline),
  873.              pch_line_len(pline) ))
  874.         return FALSE;
  875.     }
  876.     else if (strnNE(ifetch(iline, (offset >= 0)),
  877.            pfetch(pline),
  878.            pch_line_len(pline) ))
  879.         return FALSE;
  880.     }
  881.     return TRUE;
  882. }
  883.  
  884. /* Do two lines match with canonicalized white space? */
  885.  
  886. bool
  887. similar(a,b,len)
  888. Reg1 char *a;
  889. Reg2 char *b;
  890. Reg3 int len;
  891. {
  892.     while (len) {
  893.     if (isspace(*b)) {        /* whitespace (or \n) to match? */
  894.         if (!isspace(*a))        /* no corresponding whitespace? */
  895.         return FALSE;
  896.         while (len && isspace(*b) && *b != '\n')
  897.         b++,len--;        /* skip pattern whitespace */
  898.         while (isspace(*a) && *a != '\n')
  899.         a++;            /* skip target whitespace */
  900.         if (*a == '\n' || *b == '\n')
  901.         return (*a == *b);    /* should end in sync */
  902.     }
  903.     else if (*a++ != *b++)        /* match non-whitespace chars */
  904.         return FALSE;
  905.     else
  906.         len--;            /* probably not necessary */
  907.     }
  908.     return TRUE;            /* actually, this is not reached */
  909.                     /* since there is always a \n */
  910. }
  911.  
  912. /* Exit with cleanup. */
  913.  
  914. void
  915. my_exit(status)
  916. int status;
  917. {
  918.     Unlink(TMPINNAME);
  919.     if (!toutkeep) {
  920.     Unlink(TMPOUTNAME);
  921.     }
  922.     if (!trejkeep) {
  923.     Unlink(TMPREJNAME);
  924.     }
  925.     Unlink(TMPPATNAME);
  926.     exit(status);
  927. }
  928.